package com.springBoot.springBootSysCore.modules.services.system.impl;


import com.springBoot.springBootSysCore.common.StaticConfig;
import com.springBoot.springBootSysCore.common.service.IBaseServiceImpl;
import com.springBoot.springBootSysCore.common.third.pay.AlipayUtil;
import com.springBoot.springBootSysCore.common.third.pay.PayUtil;
import com.springBoot.springBootSysCore.common.third.pay.WechatUtil;
import com.springBoot.springBootSysCore.common.utils.CacheUtils;
import com.springBoot.springBootSysCore.common.utils.DateUtils;
import com.springBoot.springBootSysCore.common.utils.FileUtil;
import com.springBoot.springBootSysCore.common.utils.json.JsonUtil;
import com.springBoot.springBootSysCore.common.utils.returnUtil.CodeEnum;
import com.springBoot.springBootSysCore.common.utils.returnUtil.PageUtils;
import com.springBoot.springBootSysCore.common.utils.returnUtil.ResultJsonFormat;
import com.springBoot.springBootSysCore.modules.entity.system.SysUser;
import com.springBoot.springBootSysCore.modules.entity.utils.DictUtils;
import com.springBoot.springBootSysCore.modules.entity.utils.UserUtils;
import com.springBoot.springBootSysCore.modules.enums.AuditStateEnum;
import com.springBoot.springBootSysCore.modules.enums.PayStateEnum;
import com.springBoot.springBootSysCore.modules.enums.base.DeleteStateEnum;
import com.springBoot.springBootSysCore.modules.repository.system.SysCodeRepository;
import com.springBoot.springBootSysCore.modules.repository.system.SysRoleRepository;
import com.springBoot.springBootSysCore.modules.repository.system.SysUserRepository;
import com.springBoot.springBootSysCore.modules.services.SystemService;
import com.springBoot.springBootSysCore.modules.services.system.SysUserService;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;

import javax.persistence.criteria.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.sql.*;
import java.util.*;
import java.util.Date;

/**
 * 用户实现
 *
 * @author timo
 */
@Service
public class SysUserServiceImpl extends IBaseServiceImpl<SysUser, String> implements SysUserService {

    @Autowired
    private SysUserRepository sysUserRepository;

    @Autowired
    private SysCodeRepository sysCodeRepository;

    @Autowired
    private SysRoleRepository SysRoleRepository;
//	@Autowired
//	private BaseSysOrganizationRepository baseSysOrganizationRepository;

    @Override
    @Transactional
    public String userLogin(SysUser sysUser, String validCode, Model model, Object piccode, Boolean rememberMe) {
        model.addAttribute("account", sysUser.getAccount());
        if (StringUtils.isBlank(sysUser.getAccount()) || StringUtils.isBlank(sysUser.getPassword())) {
            model.addAttribute("user_err", "登陆失败:(用户名或者密码不能为空!)");
            return "login";
        }
        if (!piccode.toString().equalsIgnoreCase(validCode)) {
            model.addAttribute("user_err", "登陆失败:(验证码错误!)");
            return "login";
        }
        return null;
//		//密码加密了两次。所以这里加密一次，验证的时候再加密一次
//		UsernamePasswordToken token = new UsernamePasswordToken(sysUser.getAccount(),DefalCoreUitls.getMD5(sysUser.getPassword()),rememberMe);
//    	Subject currentUser = SessionUtils.getSubject();
//    	try{
//            currentUser.login(token);
//            BaseSysUser user =  baseSysUserRepository.findByAccount0(sysUser.getAccount());
//            SessionUtils.setSessionUser(user);
//            if(currentUser.isAuthenticated()){
//    			currentUser.isPermitted("-1");//强制授权
//    			return "redirect:/index/indexURL.html";
//    		}else{
//            	token.clear();
//                model.addAttribute("user_err", "登陆失败:(请检查您的用户名和密码是否正确!)");
//                return "login";
//    		}
//    	}catch (UserRealmException una){
//        	token.clear();
//        	model.addAttribute("user_err","登陆失败:("+una.getMessage()+"!)");
//            return "login";
//        } catch (UnknownAccountException uae) {
//        	token.clear();
//            model.addAttribute("user_err", "登陆失败:(请检查您的用户名和密码是否正确!)");
//            return "login";
//        } catch (IncorrectCredentialsException ice) {
//        	token.clear();
//            model.addAttribute("user_err", "登陆失败:(请检查您的用户名和密码是否正确!)");
//            return "login";
//        } catch (LockedAccountException lae) {
//        	token.clear();
//            model.addAttribute("user_err", "登陆失败:(账户已被锁定!)");
//            return "login";
//        } catch(ExcessiveAttemptsException a){
//        	token.clear();
//            model.addAttribute("user_err", "登陆失败:(账户已被锁定!)");
//            return "login";
//        }catch (AuthenticationException e) {
//        	e.printStackTrace();
//        	token.clear();
//            model.addAttribute("user_err", "登陆失败:(请检查您的用户名和密码是否正确!)");
//            return "login";
//        } catch (Exception e) {
//			e.printStackTrace();
//			 return "login";
//		}
    }

    @Override
    @Transactional
    public Map<String, Object> saveSysUser(SysUser sysUser, String roleIds, String orgIds) throws Exception {
        ResultJsonFormat rj = new ResultJsonFormat("保存成功", CodeEnum.SUCCESS.value());
        try {
//			List<String> ids = baseSysUserRepository.queryIdByAccount(baseSysUser.getAccount());
//			Map<String, Object>  map = DefalCoreUitls.crosschecking(ids, baseSysUser.getId(), rj,"账户已存在");
//			if(map!=null){
//				return map;
//			}
//			if(StringUtils.isNotBlank(baseSysUser.getPhone())){
//				ids = baseSysUserRepository.queryIdByPhone(DefalCoreUitls.encrypt(baseSysUser.getPhone(),DefalCoreConfig.DES_PASSWORD));
//				map = DefalCoreUitls.crosschecking(ids, baseSysUser.getId(), rj,"电话已存在");
//				if(map!=null){
//					return map;
//				}
//			}
//			if(StringUtils.isNotBlank(baseSysUser.getEmail())){
//				ids = baseSysUserRepository.queryIdByEmail(DefalCoreUitls.encrypt(baseSysUser.getEmail(),DefalCoreConfig.DES_PASSWORD));
//				map = DefalCoreUitls.crosschecking(ids, baseSysUser.getId(), rj,"邮箱已存在");
//				if(map!=null){
//					return map;
//				}
//			}
//			if(StringUtils.isBlank(baseSysUser.getDefalutRole().getId())){
//				baseSysUser.setDefalutRole(null);
//			}else{
//				baseSysUser.setDefalutRole(SysRoleRepository.findOne(baseSysUser.getDefalutRole().getId()));
//			}
//			if(StringUtils.isNotBlank(roleIds)){
//				baseSysUser.setRoleList(SysRoleRepository.getRoleList(DefalCoreUitls.parseJson2List(roleIds)));
//			}else{
//				baseSysUser.setRoleList(null);
//			}
//			if(StringUtils.isNotBlank(orgIds)){
//				List<String>  orgIdLi =new ArrayList<String>();
//				if(orgIds.length()<=32){
//					List<BaseSysOrganization> orgLi = new ArrayList<BaseSysOrganization>();
//					orgLi.add(baseSysOrganizationRepository.findOne(orgIds));
//					baseSysUser.setOrgList(orgLi);
//				}else{
//					orgIdLi =	DefalCoreUitls.parseJson2List(orgIds);
//					baseSysUser.setOrgList(baseSysOrganizationRepository.findOrgList(orgIdLi));
//				}
//			}else{
//				baseSysUser.setOrgList(null);
//			}
            rj.setIsUpdate(StringUtils.isNoneBlank(sysUser.getId()) ? "true" : "false");
            if (StringUtils.isBlank(sysUser.getId())) {
//				sysUser.setEmail(DefalCoreUitls.encrypt(baseSysUser.getEmail(),DefalCoreConfig.DES_PASSWORD));
//				sysUser.setPhone(DefalCoreUitls.encrypt(baseSysUser.getPhone(),DefalCoreConfig.DES_PASSWORD));
//				sysUser.setPassword(DefalCoreUitls.getMD5(DefalCoreUitls.getMD5(baseSysUser.getPassword())));
//				sysUser.setPassword(SystemService.entryptPassword(sysUser.getPassword()));
                sysUser.setPassword(SystemService.entryptPassword("111111"));
//				sysUser.setSex(0);
                sysUser.preInsert();
                if(sysUser.getBirthday()!=null){
                    sysUser.setAge(Integer.valueOf(DateUtils.getAge(sysUser.getBirthday())));
                }
                sysUserRepository.save(sysUser);
            } else {
                SysUser dbUser = sysUserRepository.getOne(sysUser.getId());//此处不取缓存
//				dbUser.setAccount(baseSysUser.getAccount());
                dbUser.EntityCopy(dbUser, sysUser);
                if(sysUser.getDefalutRole()!=null)dbUser.setDefalutRole(SysRoleRepository.findOne(sysUser.getDefalutRole().getId()));
                //上面已经赋值
//				dbSysUser.setOrgList(baseSysUser.getOrgList());
//				dbSysUser.setRoleList(baseSysUser.getRoleList());
//				dbSysUser.setDefalutRole(baseSysUser.getDefalutRole());
//				dbUser.setRealName(baseSysUser.getRealName());
//				dbUser.setEmail(DefalCoreUitls.encrypt(baseSysUser.getEmail(),DefalCoreConfig.DES_PASSWORD));
//				dbUser.setPhone(DefalCoreUitls.encrypt(baseSysUser.getPhone(),DefalCoreConfig.DES_PASSWORD));
                UserUtils.clearCache(dbUser);
//				SessionUtils.clearAllCachedAuthorizationInfo();
            }
        } catch (Exception e) {
           throw e;
        }
        return rj.convertResultJson();
    }

    @Override
    @Transactional
    public Map<String, Object> deletes(List<String> asList) {
        ResultJsonFormat ret = new ResultJsonFormat("删除成功", CodeEnum.SUCCESS.value());
        try {
            sysUserRepository.deleteByIds(asList);
        } catch (Exception e) {
            e.printStackTrace();
            ret.setMsg("删除失败");
            ret.setFlag(CodeEnum.ERROR.value());
        }
        return ret.convertResultJson();
    }

    @Override
    @Transactional
    public Map<String, Object> delete(SysUser user) {
        ResultJsonFormat rj = new ResultJsonFormat("删除成功", CodeEnum.SUCCESS.value());
        try {
            if (StringUtils.isNoneBlank(user.getId())) {
                if (user.isSureDel()) {
					sysUserRepository.delete(user.getId());
                } else {
					sysUserRepository.updateEntityById(user.getId());
                }
            } else {
                List<String> whereList = new ArrayList<String>();
                String ids = "";
                String[] a = user.getIds().split(",");
                for (int i = 0; i < a.length; i++) {
                    ids += "'" + a[i] + "'";
                    if (i != a.length - 1) {
                        ids += ",";
                    }
                }
                if (user.isSureDel()) {
                    sysUserRepository.deleteByIds(Arrays.asList(a));
                } else {
                    sysUserRepository.updateEntityByIds(Arrays.asList(a));
                }
            }
            //如果数据被使用设置为CodeEnum.Failed
            CacheUtils.remove(UserUtils.USER_CACHE);
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
        return rj.convertResultJson();
    }

    @Override
    public List<SysUser> findByIds(List<String> ids) {
        return sysUserRepository.findAllById(ids);
    }

    @Override
    public List<String> findAllIdsByAccountOrRealNamr(String queryInfo) {
        if (StringUtils.isBlank(queryInfo)) {
            return null;
        }
        return sysUserRepository.findAllIdsByAccountOrRealNamr("%" + queryInfo + "%");
    }

    @Override
    @Transactional
    public Map<String, Object> resetUserPassWord(List<String> userIds) {
        ResultJsonFormat ret = new ResultJsonFormat("操作成功", CodeEnum.SUCCESS.value());
        try {
//			sysUserRepository.resetUserPassWord(DefalCoreUitls.getMD5(DefalCoreUitls.getMD5("111111")),userIds);
        } catch (Exception e) {
            e.printStackTrace();
            ret.setMsg("操作失败");
            ret.setFlag(CodeEnum.ERROR.value());
        }
        return ret.convertResultJson();
    }

    @Override
    @Transactional
    public Map<String, Object> changeUserPassword(String oldPassword, String newPassword, Model model, Object piccode, String validCode) {
        ResultJsonFormat ret = new ResultJsonFormat("您好,您的密码修改成功", CodeEnum.SUCCESS.value());
        try {
            if (!piccode.toString().equalsIgnoreCase(validCode)) {
                ret.setFlag(CodeEnum.ERROR.value());
                ret.setMsg("抱歉,验证码输入不正确");
                return ret.convertResultJson();
            }
            if (StringUtils.isBlank(oldPassword)) {
                ret.setFlag(CodeEnum.ERROR.value());
                ret.setMsg("抱歉,旧密码不能为空");
                return ret.convertResultJson();
            }
            if (StringUtils.isBlank(newPassword)) {
                ret.setFlag(CodeEnum.ERROR.value());
                ret.setMsg("抱歉,新密码不能为空");
                return ret.convertResultJson();
            }
            SysUser user = UserUtils.getUser();
            if (!SystemService.validatePassword(oldPassword, user.getPassword())) {
                ret.setFlag(CodeEnum.ERROR.value());
                ret.setMsg("抱歉,您输入的旧密码不正确");
                return ret.convertResultJson();
            }
            SysUser sysUser = sysUserRepository.findOne(user.getId());
            sysUser.setPassword(SystemService.entryptPassword(oldPassword));
            UserUtils.clearCache(user);
        } catch (Exception e) {
            e.printStackTrace();
            ret.setFlag(CodeEnum.ERROR.value());
            ret.setMsg("抱歉,您的密码修改失败");
        }
        return ret.convertResultJsonForData();
    }

    @Override
    public Object checkUserName(String account, String id) {
        List<String> ids = sysUserRepository.queryIdByAccount(account);
        return crosschecking(ids, id);
    }

    @Override
    @Transactional
    public Map<String, Object> updateStateById(String id, String available) {
        ResultJsonFormat ret = new ResultJsonFormat("操作成功", CodeEnum.SUCCESS.value());
        try {
            SysUser u = sysUserRepository.findOne(id);
            u.setAvailable(available);
        } catch (Exception e) {
            e.printStackTrace();
            ret.setMsg("操作失败");
            ret.setFlag(CodeEnum.ERROR.value());
        }
        return ret.convertResultJson();
    }

    @Override
    @Transactional
    public Map<String, Object> resetLoginPwd(String id, String password) {
        ResultJsonFormat ret = new ResultJsonFormat("操作成功", CodeEnum.SUCCESS.value());
        try {
            sysUserRepository.resetUserPassWord(password, id);
        } catch (Exception e) {
            e.printStackTrace();
            ret.setMsg("操作失败");
            ret.setFlag(CodeEnum.ERROR.value());
        }
        return ret.convertResultJson();
    }

    @Override
    public List<Map<String, Object>> findSelect(String userType) {
        List<Object[]> list = sysUserRepository.findSelect(userType);
        String[] li = new String[]{"id", "nickName"};
        List<Map<String, Object>> lis = JsonUtil.castEntity(list, li);
        return lis;
    }

    @Override
    public void memberPayOk(HttpServletRequest request, HttpServletResponse response) {
        System.out.println("*********************收到回调************************");
        try{
            Map<String,String> params = AlipayUtil.getAlipayParams(request);
            System.out.println("*************************支付宝返回参数为:*****************************");
            System.out.println(params);
            String payWay = "alipay";
            //如果不是支付宝，再用微信验证一次
            if(!AlipayUtil.alipayVerify(params)){
                params = WechatUtil.getWechatParams(request);
                System.out.println("*****************微信返回参数:*******************");
                System.out.println(params);
                if(WechatUtil.wechatVerify(params)){
                    payWay = "wechat";
                }else{
                    payWay = "";
                }
            }
            System.out.println("********************支付方式为:"+payWay+"*******************");
            if("alipay".equals(payWay)){
                //refund_status:退款状态   当值为空，说明是支付时调用，如果是REFUND_SUCCESS，说明是退款时调用
                if(!StringUtils.isNotEmpty(params.get("refund_status")) && "TRADE_SUCCESS".equals(params.get("trade_status"))){//表示是支付宝支付成功后的回调
                    String indentNum = params.get("out_trade_no");//订单号
                    String trade_no = params.get("trade_no");//交易号

//                    UserFeesLog ul =userFeesLogRepository.findByTradeNo(trade_no);
//                    if(ul==null){
//                        memberAccomplishHandle(indentNum,trade_no);//商品订单完成后的操作
//                    }
                }
                AlipayUtil.returnState(response, "TRADE_SUCCESS".equals(params.get("trade_status")));
            }else if("wechat".equals(payWay)){
                if("SUCCESS".equals(params.get("return_code"))){
                    String indentNum = params.get("out_trade_no");//订单号
                    String trade_no = params.get("transaction_id");//三方交易号

//                    UserFeesLog ul =userFeesLogRepository.findByTradeNo(trade_no);
//                    if(ul==null){
//                        memberAccomplishHandle(indentNum,trade_no);//商品订单完成后的操作
//                    }
                }
                System.out.println("********************返回结果:"+("SUCCESS".equals(params.get("return_code")))+"*******************");
                WechatUtil.returnState(response, "SUCCESS".equals(params.get("return_code")));
            }
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 运单支付成功更新交易号、支付状态
     * hx 2017年10月19日 下午2:55:47
     * @param indentNum
     * @param tradeNo
     */
    @Transactional
    private void memberAccomplishHandle(String indentNum, String tradeNo){
//        UserFeesLog uf = userFeesLogRepository.findByOrderNo(indentNum);
////		userFeesLogRepository.updateTradeNo(indentNum,tradeNo);
//        uf.setTradeNo(tradeNo);
//        uf.setPayDate(new Date());
//        uf.setPayState(PayStateEnum.YES_PAY.getName());
//        SysUser sysu = uf.getSysUser();
//        sysu.setMember("1");
//        sysu.setMemberDate(DateUtils.getDateAfterWhatMSForDate(new Date(),365));
    }
}
